class Ajax {
    /*   
ajax({
    method: "get",
    url: "http://localhost:8088/api/list",
    data:{},
    execute:(data)=>{
        console.log(data);
    },
    err:(data)=>{
       console.log("xml.readyState"+data.readyState); 
       console.log("xml.status"+data.status); 
    }
}) 
    */
    ajax(option) {
        let xml = new XMLHttpRequest()
        let dataStr = ""
        dataStr=option.data&&this.parseDate(option.data)
        let method = option.method.toUpperCase()
        if (method == "GET") {
            xml.open(method, option.url + "?" + dataStr)
            xml.send()
        } else if (method == "POST") {
            xml.open(method, option.url)
            xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            if(option.header){
                for(let value in option.header){
                    xml.setRequestHeader(`${value}`,option.header[value]);
                }
            }
            xml.send(dataStr)
        }
        xml.withCredentials = true
        xml.onreadystatechange = function () {
            if (xml.readyState == 4) {
                if (xml.status == 200) {
                    let data = JSON.parse(xml.responseText)
                    option.execute && option.execute(data)
                } else {
                    option.err && option.err(this)
                    console.log("状态码："+xml.status);
                }
            }
        }
    }
    parseDate(date) {
        let datearr = []
        for (let value in date) {
            datearr.push(`${value}=${date[value]}`)
        }
        return datearr.join("&")
    }
}

function parseDate(date) {
    let datearr = []
    for (let value in date) {
        datearr.push(`${value}=${date[value]}`)
    }
    return datearr.join("&")
}

function promise(option){
    return new Promise(function(resolve, reject){
        let xml = new XMLHttpRequest()
        let dataStr = ""
        dataStr=option.data&&this.parseDate(option.data)
        let method = option.method.toUpperCase()
        if (method == "GET") {
            xml.open(method, option.url + "?" + dataStr)
            xml.send()
        } else if (method == "POST") {
            xml.open(method, option.url)
            xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            if(option.header){
                for(let value in option.header){
                    xml.setRequestHeader(`${value}`,option.header[value]);
                }
            }
            if(option.cookie){

            }
            xml.send(dataStr)
        }
        xml.onreadystatechange = function () {
            if (xml.readyState == 4) {
                if (xml.status == 200) {
                    let data = JSON.parse(xml.responseText)
                     resolve(data)
                } else {
                    reject(this)
                }
            }
        }
    })
}